/**
 * Created by 何立 on 2017/3/20.
 */
//检查是否登录，如果没有登录跳转至登录界面
$(document).ready(function () {
    if (location.pathname != '/reg_login') {
        //console.log(typeof($.cookie('loginToken')));
        //console.log($.cookie('loginToken'));
        if ($.cookie('loginToken') == '' || typeof($.cookie('loginToken')) == "undefined" || $.cookie('loginToken') == 'null') {
            location.pathname = '/reg_login';
        }
    }
});

//获取个人信息
$(document).ready(function () {
    $.post("http://123.206.80.54:7000/user/query", {
            loginToken: $.cookie('loginToken')
        },
        function (status, error, res) {
            var info = res.responseJSON.res;
            var form = $('#personal-form');
            form.find("[name='nickname']").val(info.nickname);
            //console.log(info.sex);
            if (info.sex == 1) {
                form.find("[name='sex']").eq(0).attr("checked", 'checked');
            } else {
                form.find("[name='sex']").eq(1).attr("checked", 'checked');
            }
            form.find("[name='school']").val(info.school);
            form.find("[name='address']").val(info.address);
            form.find("[name='description']").val(info.description);
            form.find("[name='birthday']").val(info.birthday);
            $('.info-nickname').text(info.nickname);
            //console.log(info.picturePath);
            $('.info-head').attr('src','http://123.206.80.54:7000/file/download/' + info.picturePath);
        }, 'json');
});

//获取用户已加入课程和班级成员列表
$(document).ready(function () {
    $.post("http://123.206.80.54:7000/class/query", {
            loginToken: $.cookie('loginToken')
        },
        function (status, error, res) {
            var course_statuses = $('#course-status');
            var course_status = '';
            var new_questions =  $('#course-new-question');
            var question = '';

            var courses_info = res.responseJSON.res;
            var course_select = $('#homework-course-select');
            var select_project = $('#select-project');
            var nav = $('#course-nav');
            var nav_content = $('#course-nav-content');
            var nav_child = '';
            var nav_div = '';
            var course_info;
            var course_counter;
            var course_panel;
            for (var i = 0; i < courses_info.length; i++) {
                course_info = courses_info[i];
                if(i == 0){
                    nav_child = '<li><a onclick="article_list_get(event)" href="#' + course_info.id + '" data-toggle="tab">' +
                       course_info.className + '</a></li>';
                    nav_div = '<div class="tab-pane fade in active" id="' + course_info.id + '"></div>';
                }else{
                    nav_child = '<li><a onclick="article_list_get(event)" href="#' + course_info.id + '" data-toggle="tab">' +
                        course_info.className + '</a></li>';
                    nav_div = '<div class="tab-pane fade" id="' + course_info.id + '"></div>';
                }
                nav.append(nav_child);
                nav_content.append(nav_div);

                course_status = '<li>\
                <p class="circle circle-1"></p>\
                    <p class="name">' + course_info.className + '<!--课程名-->\
                    <p class="count">\
                    <a href="/homework_check"><span\
            class="crr">去批改</span></a>\
                    </p>\
                    </li>';
                course_statuses.append(course_status);

                question = '<li>\
                    <p class="circle circle-1"></p>\
                    <p class="name">' + course_info.className + '</p>\
                    <p class="count">\
                    <a href="/source"><span\
            class="crr">去查看</span></a>\
                    </p>\
                    </li>';
                new_questions.append(question);

                var option = '<option value="' + course_info.id + '">' + course_info.className + '</option>';
                select_project.append(option);
                var check_box = '<p style="margin-left: 24px;*margin-left: 12px; width: 88px;"\
            class="w-checkbox-current">\
                    <input type="checkbox" name="homework-course" value="' + course_info.id + '"/>\
                    <span class="w-icon-md" style="width:70px;">' + course_info.className + '</span>\
                    </p>';
                course_select.append(check_box);


                course_counter = 'collapse' + i;
                var table_list = '<table class="table table-hover .table-bordered table-condensed course-member-table">\
            <tr>\
            <th>昵称</th>\
            <th>性别</th>\
            <th>类别</th>\
            <th>电话</th>\
            <th>操作</th>\
            </tr>';
                $.ajax({
                    url : "http://123.206.80.54:7000/class/list",
                    async : false, // 注意此处需要同步
                    type : "POST",
                    dataType : "json",
                    data : {
                        loginToken: $.cookie('loginToken'),
                        classId : course_info.id
                    },
                    success : function(status, error, res) {
                        var members = res.responseJSON.res;
                        for(var j = 0; j < members.length; j++){
                            var Type;
                            if(members[j].type == 1){
                                Type = "学生";
                            }else{
                                Type = "老师";
                            }
                            table_list += '<tr><td>' + members[j].nickname + '</td><td>' + members[j].sex + '</td><td>' +
                                Type + '</td><td>' + members[j].mobile + '</td><td>' +
                                '<input type="test" hidden value="' + course_info.id + '"/>' +
                                '<button class="btn btn-danger" value="' + members[j].id + '"' +
                                ' onclick="course_exclude(event)">踢出</button></td></tr>';
                        }
                        table_list += '</table>';
                    }
                });
                if(i == 0){
                    course_panel = '<div class="panel panel-default">\
                <div class="panel-heading" role="tab" id="heading' + i + '">\
                    <h4 class="panel-title">\
                    <div class="row" style="margin: 0;text-align: center">\
                    <div class="col-xs-10" style="padding-top: 10px">\
                    <a role="button" data-toggle="collapse" data-parent="#accordion"\
                href=#' + course_counter + ' aria-expanded="true" aria-controls="' + course_counter + '">' + course_info.className +'\
                    </a>\
                    </div>\
                    <div class="col-xs-2">\
                    <button type="button" class="btn btn-danger class-relete" \
                    value="' + course_info.id + '" onclick="course_delete(event)">删除</button>\
                    </div>\
                    </div>\
                    </h4>\
                    </div>\
                    <div id="' + course_counter + '" class="panel-collapse collapse in" role="tabpanel"\
                aria-labelledby="heading' + i + '">\
                    <div class="panel-body">' + course_info.description + table_list +
                        ' </div >\
            </div >\
            </div > ';
                }else{
                    course_panel = '<div class="panel panel-default">\
                <div class="panel-heading" role="tab" id="heading' + i + '">\
                    <h4 class="panel-title">\
                    <div class="row" style="margin: 0;text-align: center">\
                    <div class="col-xs-10" style="padding-top: 10px">\
                    <a role="button" class="collapsed" data-toggle="collapse" data-parent="#accordion"\
                href=#' + course_counter + ' aria-expanded="false" aria-controls="' + course_counter + '">' + course_info.className +'\
                    </a>\
                    </div>\
                    <div class="col-xs-2">\
                    <button type="button" class="btn btn-danger" \
                    value="' + course_info.id + '" onclick="course_delete(event)">删除</button>\
                    </div>\
                    </div>\
                    </h4>\
                    </div>\
                    <div id="' + course_counter + '" class="panel-collapse collapse" role="tabpanel"\
                aria-labelledby="heading' + i + '">\
                    <div class="panel-body">' + course_info.description + table_list + '</div >\
            </div >\
            </div > ';
                }
                $('.course-group').append(course_panel);
                //console.log("课程id"+course_info.id);
            }
        }, 'json');
});

//切换作业上传方式
$('#upload_button>li').click(function () {
    var upload_buttons = $('#upload_button>li');
    var index = upload_buttons.index(this);
    upload_buttons.removeClass("active");
    $(this).addClass("active");
    var question_lists = $("#tabContent>div");
    for (var i = 0; i < 3; i++) {
        if (i != index) {
            question_lists.eq(i).css("display", "none");
        } else {
            question_lists.eq(i).css("display", "block");
        }
    }
});

//日期选择器
//$('#homework-deadline').datetimepicker();

//城市选择器
$('#city-picker').citypicker();

//统计功能，作业完成时间统计
(function () {
    var statistic_time = echarts.init(document.getElementById('statistic-time'));
// 指定图表的配置项和数据
    var option = {
        title: {
            text: '作业完成时间统计',
            padding: [0, 0, 100, 0]
        },
        series: [
            {
                name: '作业完成时间统计',
                type: 'pie',
                radius: '60%',
                data: [
                    {value: 0.60, name: 'A 60%'},
                    {value: 0.20, name: 'B 20%'},
                    {value: 0.15, name: 'C 15%'},
                    {value: 0.05, name: 'D 5%'}

                ]
            }
        ]
    };
// 使用刚指定的配置项和数据显示图表。
    statistic_time.setOption(option);
})();

//统计功能，作业完成品质统计
(function () {
    var statistic_quailty = echarts.init(document.getElementById('statistic-quality'));
// 指定图表的配置项和数据
    var option = {
        title: {
            text: '作业完成品质统计'
        },
        series: [
            {
                name: '作业完成品质统计',
                type: 'pie',
                radius: '60%',
                data: [
                    {value: 0.60, name: 'A 60%'},
                    {value: 0.20, name: 'B 20%'},
                    {value: 0.15, name: 'C 15%'},
                    {value: 0.05, name: 'D 5%'}

                ]
            }
        ]
    };
// 使用刚指定的配置项和数据显示图表。
    statistic_quailty.setOption(option);
})();

//统计功能，学生作业完成时间情况
(function () {
    var student_time = echarts.init(document.getElementById('student-time'));
// 指定图表的配置项和数据
    option = {
        title: {
            text: '学生作业完成时间情况'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'time'
        },
        yAxis: {
            type: 'category',
            data: ['张三', '李四', '王五', '赵六', '何七', '王八']
        },
        series: [
            {
                name: '开始时间',
                type: 'bar',
                stack: '总量',
                itemStyle: {normal: {color: 'rgba(0,0,0,0)'}},
                data: [
                    new Date("2015/09/02"),
                    new Date("2015/09/02"),
                    new Date("2015/09/02"),
                    new Date("2015/09/02"),
                    new Date("2015/09/02"),
                    new Date("2015/09/02")
                ]
            },
            {
                name: '完成时间',
                type: 'bar',
                stack: '总量',
                data: [
                    new Date("2015/09/12"),
                    new Date("2015/09/20"),
                    new Date("2015/09/25"),
                    new Date("2015/09/05"),
                    new Date("2015/09/07"),
                    new Date("2015/09/09")
                ]
            }
        ]
    };
// 使用刚指定的配置项和数据显示图表。
    student_time.setOption(option);
})();

//统计功能，学生分数
(function () {
    var student_quailty = echarts.init(document.getElementById('student-quality'));
    option = {
        title: {
            text: '学生分数'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        yAxis: {
            type: 'category',
            data: ['张三', '李四', '王五', '赵六', '何七', '王八']
        },
        series: [
            {
                name: '分数',
                type: 'bar',
                data: [25, 38, 10, 94, 51, 87]
            }
        ]
    };
    student_quailty.setOption(option);
})();

//免费注册
function reg_1_to_reg_2() {
    $('#reg-login-1ink').css('display', 'none');
    $('#reg-1').css('display', 'none');
    $('#reg-2').css('display', 'block');
}

//接收验证码
function reg_2_to_reg_3() {
    var form = $('#reg-form');
    var Code = form.find("[name='code']").val();
    var Mobile = form.find("[name='mobile']").val();
    if (Code == '' || Mobile == '') {
        alert("输入框不能为空");
    } else {
        $('#reg-2').css('display', 'none');
        $('#reg-3').css('display', 'block');
    }
}

//批改作业，切换至下一题
function next_quesiton(event) {
    var this_list = $(event.target).parents('.homework-check-list');
    var list = $('.homework-check-list');
    var index = list.index(this_list);
    var answer_list = $('.panel-group');
    if(this_list.next().length){
        this_list.css('display','none');
        this_list.next().css('display','block');
        answer_list.eq(index).css('display','none');
        answer_list.eq(index).next().css('display','block');
    }
}

//批改作业，切换至上一题
function prev_quesiton(event) {
    var this_list = $(event.target).parents('.homework-check-list');
    var list = $('.homework-check-list');
    var index = list.index(this_list);
    var answer_list = $('.panel-group');
    if(this_list.prev().length){
        this_list.css('display','none');
        this_list.prev().css('display','block');
        answer_list.eq(index).css('display','none');
        answer_list.eq(index).prev().css('display','block');
    }
}

/**************************************************
 以下是AJAX或表单相关
 **************************************************/
//请求发送短信并验证码倒计时
function validate_click() {
    var validate_button = $('#validate-button');
    validate_button.attr('disabled', true);
    var time = 10;
    var clock = setInterval(function () {
        validate_button.text(time + "秒后可点击");
        time--;
        if (time < 0) {
            time = clearInterval(clock);
            validate_button.text("获取验证码");
            validate_button.attr('disabled', false);
        }
    }, 1000);
    var Mobile = $('#reg-form').find("[name='mobile']").val();
    //console.log(Mobile);
    $.post("http://123.206.80.54:7000/user/validate", {
            mobile: Mobile
        },
        function (status, error, res) {
            //console.log("响应：" + res + "状态：" + status + "错误" + error);
            //console.log(res.responseText);
            //console.log(res.responseJSON.res);
            //console.log(res.responseJSON.res.mobileToken);
            $.cookie('mobileToken', res.responseJSON.res.mobileToken);
        }, 'json');
}

//找回密码时发送短信并验证码倒计时
function pwd_validate_click() {
    var validate_button = $('#pwd-validate-button');
    validate_button.attr('disabled', true);
    var time = 10;
    var clock = setInterval(function () {
        validate_button.text(time + "秒后可点击");
        time--;
        if (time < 0) {
            time = clearInterval(clock);
            validate_button.text("获取验证码");
            validate_button.attr('disabled', false);
        }
    }, 1000);
    var Mobile = $('#pwd-form').find("[name='mobile']").val();
    //console.log(Mobile);
    if (!Mobile) {
        console.log("test");
        var Username = $('#pwd-form').find("[name='username']").val();
        //console.log(Username);
        $.post("http://123.206.80.54:7000/user/validate", {
                username: Username
            },
            function (status, error, res) {
                $.cookie('mobileToken', res.responseJSON.res.mobileToken);
            }, 'json');
    } else {
        //console.log(Mobile,Username);
        $.post("http://123.206.80.54:7000/user/validate", {
                mobile: Mobile
            },
            function (status, error, res) {
                $.cookie('mobileToken', res.responseJSON.res.mobileToken);
            }, 'json');
    }
}

//注册表单提交
function reg_click() {
    $('#reg-click-button').attr('disabled', true);
    var form = $('#reg-form');
    var Type = 2;
    var Username = form.find("[name='username']").val();
    var Password = form.find("[name='password']").val();
    var Password_repeat = form.find("[name='password_repeat']").val();
    var MobileToken = $.cookie('mobileToken');
    var Code = form.find("[name='code']").val();
    var Mobile = form.find("[name='mobile']").val();
    if(Password != Password_repeat){
        alert("两次密码输入不一致");
    }else{
        $.post("http://123.206.80.54:7000/user/create", {
                type: Type,  //0 = admin, 1 = student, 2 = teacher
                username: Username, //不能为纯数字
                password: Password,
                mobile: Mobile,  //must be number
                mobileToken: MobileToken, //填入短信验证时返回的结果
                code: Code //填入手机收到的验证码
            },
            function (status, error, res) {
                //console.log("响应：" + res + "状态：" + status + "错误" + error);
                $.cookie('loginToken', res.responseJSON.res.loginToken, {path: '/'});
                location.pathname = '/';
            }, 'json');
    }
    //console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
    //console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
    //+ typeof(Code) + ' ' + typeof(Mobile));
}

//登录表单提交
function login_click() {
    $('#login-button').attr('disabled', true);
    var form = $('#login-form');
    var Account = form.find("[name='account']").val();
    var Password = form.find("[name='password']").val();
    var Remember = 7200;
    $.post("http://123.206.80.54:7000/user/login", {
            account: Account,
            password: Password,
            remember: Remember
        },
        function (status, error, res) {
            $.cookie('loginToken', res.responseJSON.res.loginToken, {path: '/'});
            location.pathname = '/';
        }, 'json');
}

//个人信息提交
function personal_confirm_click() {
    var form = $('#personal-form');
    var Nickname = form.find("[name='nickname']").val();
    var Sex = parseInt(form.find("input[name='sex'][checked]").val());
    var School = form.find("[name='school']").val();
    var Address = form.find("[name='address']").val();
    var Description = form.find("[name='description']").val();
    var Birthday = form.find("[name='birthday']").val();
    var PicturePath = form.find("[name='picturePath']").val();

    //console.log($.cookie('loginToken'), Nickname, Sex, School, Address, Description, Birthday,PicturePath,FileName);
    //console.log(typeof($.cookie('loginToken')), typeof(Nickname), typeof(Sex), typeof(School),
        //typeof(Address), typeof(Description), typeof(Birthday));
    var file = new FormData(form[0]);
    $.ajax({
        url: "http://123.206.80.54:7000/file/upload",
        type: 'POST',
        data: file,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (status, error, res) {
            PicturePath = res.responseJSON.res[0].path;
            FileName = res.responseJSON.res[0].filename;
            //console.log($.cookie('loginToken'), Nickname, Sex, School, Address, Description, Birthday,PicturePath,FileName);
            $.post("http://123.206.80.54:7000/user/change", {
                    loginToken: $.cookie('loginToken'),
                    nickname: Nickname,
                    sex: Sex,  //0 = female, 1 = male, 2...
                    school: School,
                    address: Address,
                    description: Description, //个性签名
                    birthday: Birthday,//xxxx-xx-xx形式
                    picturePath : PicturePath, //头像, 填入上传返回的path
                    fileName : FileName //填入头像的文件名
                },
                function (status, error, res) {
                    console.log(status + ' ' + error + ' ' + res);
                }, 'json');
        },
        error: function (status, error, res) {
        }
    });
    $('.personal-data').find('input').attr('disabled', true);
    $('#login-button').attr('disabled', true);
}

//用户退出
function user_exit() {
    $.cookie('loginToken', null);
    window.location.reload();
}

function pwd_1_to_pwd_2() {
    $('#reg-1').css('display', 'none');
    $('#pwd-2').css('display', 'block');
    $('#reg-login-1ink').css('display', 'none');
}

//接收验证码
function pwd_2_to_pwd_3() {
    var form = $('#pwd-form');
    var Code = form.find("[name='code']").val();
    var Mobile = form.find("[name='mobile']").val();
    var Username = form.find("[name='username']").val();
    if (Code == '' || (Mobile == '' && Username == '')) {
        alert("输入框不能为空");
    } else {
        $('#pwd-2').css('display', 'none');
        $('#pwd-3').css('display', 'block');
    }
}

//修改密码表单提交
function pwd_click() {
    $('#pwd-click-button').attr('disabled', true);
    var form = $('#pwd-form');
    var Password = form.find("[name='password']").val();
    var MobileToken = $.cookie('mobileToken');
    var Code = form.find("[name='code']").val();
    var Username = form.find("[name='username']").val();
    if (!Username) {
        var Mobile = form.find("[name='mobile']").val();
        $.post("http://123.206.80.54:7000/user/forget", {
                mobile: Mobile,  //must be number
                mobileToken: MobileToken, //填入短信验证时返回的结果
                password: Password,
                code: Code //填入手机收到的验证码
            },
            function (status, error, res) {
                console.log("响应：" + res + "状态：" + status + "错误" + error);
                location.pathname = '/';
            }, 'json');
    } else {
        $.post("http://123.206.80.54:7000/user/forget", {
                username: Username, //不能为纯数字
                mobileToken: MobileToken, //填入短信验证时返回的结果
                password: Password,
                code: Code //填入手机收到的验证码
            },
            function (status, error, res) {
                console.log("响应：" + res + "状态：" + status + "错误" + error);
                location.pathname = '/';
            }, 'json');
    }
    //console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
    //console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
    //+ typeof(Code) + ' ' + typeof(Mobile));
}

//创建课程
function create_course() {
    $('#create-course-button').attr('disabled', true);
    var form = $('#create-course-form');
    var ClassName = form.find("[name='courseName']").val();
    var tags = form.find("[name='tags']").val().split(" ");
    var Description = form.find("[name='description']").val();
    console.log(tags);

    $.post("http://123.206.80.54:7000/class/create", {
            loginToken: $.cookie('loginToken'),
            className: ClassName,
            description: Description,
            tags: tags
        },
        function (status, error, res) {
            var course = res.responseJSON.res;
            //console.log("响应：" + res + "状态：" + status + "错误" + error);
            //console.log(course.classname, course.id, course.description);
            location.reload();
        }, 'json');
}

//删除课程
function course_delete() {
    var panel = $(event.target).parents('.panel');
    var ClassId = $(event.target).val();
    $.post("http://123.206.80.54:7000/class/remove", {
            loginToken: $.cookie('loginToken'),
            classId : ClassId
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
            panel.remove();
        }, 'json');
}

//查找课程
function course_find() {
    var form = $('#add-course-form');
    var Tags = form.find("[name='tags']").val().split(' ');
    if(form.find("[name='tags']").val() == ''){
        var Names = form.find("[name='courseName']").val().split(' ');
        $.post("http://123.206.80.54:7000/class/getbyname", {
                names : Names
            },
            function (status, error, res) {
                console.log("响应：" + res.responseJSON.res + "状态：" + status + "错误" + error);
                var courses_info = res.responseJSON.res;
                var table = $('.course-table');
                table.empty();
                var table_list = '<tr><th>课程名</th> <th>描述</th><th>操作</th></tr>';
                for(var i = 0; i < courses_info.length; i++){
                    table_list += '<tr><td>' + courses_info[i].className + '</td><td>'+ courses_info[i].description + '</td>' +
                        '<td><button class="btn btn-success course-join-button" onclick="course_join()" value="' + courses_info[i].id + '">加入</button></td></tr>';
                }
                table.append(table_list);
            }, 'json');
    }else{
        $.post("http://123.206.80.54:7000/class/getbytag", {
                tags : Tags
            },
            function (status, error, res) {
                console.log("响应：" + res.responseJSON.res + "状态：" + status + "错误" + error);
                var courses_info = res.responseJSON.res;
                var table = $('.course-table');
                table.empty();
                var table_list = '<tr><th>课程名</th> <th>描述</th><th>操作</th></tr>';
                for(var i = 0; i < courses_info.length; i++){
                    table_list += '<tr><td>' + courses_info[i].className + '</td><td>'+ courses_info[i].description + '</td>' +
                        '<td><button class="btn btn-success course-join-button" onclick="course_join()" value="' + courses_info[i].id + '">加入</button></td></tr>';
                }
                table.append(table_list);
            }, 'json');
    }

}

//加入课程
function course_join() {
    var ClassId = $(event.target).val();
    $.post("http://123.206.80.54:7000/class/join", {
            loginToken: $.cookie('loginToken'),
            classId : ClassId
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
            location.reload();
        }, 'json');
}

//踢出学生
function course_exclude(event) {
    var UserId = $(event.target).val();
    var ClassId = $(event.target).prev().val();
    $.post("http://123.206.80.54:7000/user/exclude", {
            loginToken: $.cookie('loginToken'),
            classId : ClassId,
            userId : UserId
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
            $(event.target).parents('tr').remove();
        }, 'json');
}

//创建作业并上传与作业关联的附件
function homework_create() {
    var form = $('#homework-post-form');
    var Title = form.find("[name='homework-title']").val();
    var Content = form.find("[name='instruction']").val();
    var Author = form.find("[name='homework-author']").val();
    var Difficulty = parseInt(form.find("[name='homework-level']").val());
    var Type = parseInt(form.find("input[name='isChecked'][checked]").val());
    var Tags = form.find("[name='homework-tags']").val().split(' ');
    var Answers = form.find("[name='homework-answer']").val();
    var file = new FormData(form[0]);
    if(!Answers){
        //console.log("test");
    }else{
        Answers = Answers.split(' ');
    }
    //console.log(Answers);
    var Select = $('#homework-course-select').find("[name='homework-course']:checked");
    var Score = parseInt(form.find("[name='homework-score']").val());
    var Deadline = form.find("[name='homework-deadline']").val();
    var Classes = new Array();
    //console.log(Select.length);
    for(var i = 0; i < Select.length; i++){
        Classes[i] = {
            classId : Select[i].value,
            score : Score,
            deadline : Deadline
        }
    }
    //console.log(typeof(Title),typeof(Content),typeof(Author),typeof(Difficulty),typeof(Type),typeof(Tags),typeof(Classes),typeof(Answers));
    //console.log(Title,Content,Author,Difficulty,Type,Tags,Classes,Answers);
    $.post("http://123.206.80.54:7000/homework/create", {
            loginToken : $.cookie('loginToken'),
            title : Title,
            content : Content,
            author : Author,
            difficulty : Difficulty, //0-5
            type : Type, //0 = auto judgement, 1 = manual judgement
            tags : Tags, //ARRAY of tagName ["web","android"]
            classes : Classes, //[{classId : STRING, score : INTEGER, deadline : STRING}, ...]//
            answers : Answers //选择题答案用大写字母表示, 判断用T/F, 之所以用数组是因为一道题答案
            // 可以有多个选项;数组元素必须是单个字母 示例"['A','C']", 注意最外边的引号,以及内部单引号
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
            var HomeworkId = res.responseJSON.res.homeworkId;
            $.ajax({
                url: "http://123.206.80.54:7000/file/upload",
                type: 'POST',
                data: file,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (status, error, res) {
                    var Path = res.responseJSON.res[0].path;
                    var Filename = res.responseJSON.res[0].filename;
                    $.post("http://123.206.80.54:7000/homework/attach", {
                            loginToken : $.cookie('loginToken'),
                            path : Path, //填入服务器返回的路径
                            filename : Filename, //填入源文件名
                            homeworkId : HomeworkId //id of homework
                        },
                        function (status, error, res) {
                            console.log("响应：" + res + "状态：" + status + "错误" + error);
                            location.reload();
                        }, 'json');
                },
                error: function (status, error, res) {
                }
            });
            }, 'json');
}

//获取作业详情和附件，查看当前课程已留作业列表，查询学生作业完成情况
function homework_get() {
    var form = $('#homework-check-get-form');
    var ClassId = form.find("[name='project']").val();
    $.post("http://123.206.80.54:7000/teach/assignList", {
            loginToken: $.cookie('loginToken'),
            classId : ClassId
        },
        function (status, error, res) {
            //console.log("响应：" + res + "状态：" + status + "错误" + error);
            assignments = res.responseJSON.res;
            var homework_check_question = $('#homework-check-question');
            var panel_group = '';
            var panel_counter = 0;
            homework_check_question.empty();
            for (var i = 0; i < assignments.length; i++) {
                var HomeworkId = assignments[i].homeworkId;
                var Score = assignments[i].score;
                $.ajax({
                    url: "http://123.206.80.54:7000/homework/info",
                    async: false, // 注意此处需要同步
                    type: "POST",
                    dataType: "json",
                    data: {
                        homeworkId: HomeworkId
                    },
                    success: function (status, error, res) {
                        var homework = res.responseJSON.res;
                        var link = '';
                        for (var j = 0; j < homework.attachments.length; j++) {
                            link += '<a href="' + 'http://123.206.80.54:7000/file/download/' +
                                homework.attachments[j].path + '">查看附件' + j + '</a>';
                        }
                        var list = '<div class="homework-check-list">\
                            <h4>作业标题：' + homework.title + i + '    满分：' + Score + '</h4>\
                            <div class="homework-show">' + homework.content + '</div>\
                            <div>' + link +
                            '<div style="display: inline-block;float: right">\
                            <button class="btn btn-primary" style="margin-right: 20px" onclick="prev_quesiton(event)">上一题</button>\
                            <button class="btn btn-primary" onclick="next_quesiton(event)">下一题</button>\
                            </div>\
                            </div>\
                            </div>';
                        homework_check_question.append(list);
                        //console.log("响应：" + res + "状态：" + status + "错误" + error);
                    }
                });
                //console.log("assignments[i].assignId" + assignments[i].assignId);
                $.ajax({
                    url : "http://123.206.80.54:7000/teach/finishingList",
                    async : false, // 注意此处需要同步
                    type : "POST",
                    dataType : "json",
                    data : {
                        loginToken: $.cookie('loginToken'),
                        assignId : assignments[i].assignId
                    },
                    success: function (status, error, res){
                        var finishings = res.responseJSON.res;
                        var panel = '';
                        var link = '';
                        var style = '';
                        if(panel_counter != 0){
                            style = 'style="display: none"';
                        }
                        var homework_check_student = $('#homework-check-student');
                        //homework_check_student.empty();

                        panel_group = '<div class="panel-group homework-check-student-panels" id="accordion-' + panel_counter + '" ' +
                            'role="tablist" aria-multiselectable="true"' + style + '>';
                        //var homework_check_student_panels = $('.homework-check-student-panels');
                        for(var j = 0; j < finishings.length; j++){
                            var answer = finishings[j].answer;
                            //console.log("我是answer",answer);
                            for(var k = 0; k < finishings[j].attachments.length; k++){
                                link += '<a href="' + 'http://123.206.80.54:7000/file/download/' +
                                    finishings[j].attachments[k].path + '">查看附件' + k + '</a>';
                            }
                            panel = '<div class="panel panel-default student-answer-list">\
                        <div class="panel-heading" role="tab" id="heading-' + panel_counter + j  +  '" style="padding: 0">\
                        <h4 class="panel-title">\
                        <div class="row" style="margin: 0;text-align: center">\
                        <div class="col-xs-8" style="padding-top: 10px">\
                        <a class="col-xs-8" role="button" data-toggle="collapse"\
                    data-parent="#accordion-' + panel_counter + '"\
                    href="#collapse-' + panel_counter + j + '" aria-expanded="true"\
                    aria-controls="collapse-' + panel_counter + j + '">' + finishings[j].nickname + '</a>\
                        </div>\
                        <form class="col-xs-4 form-inline check-score-form">\
                        <div class="form-group">\
                        <label for="test">分数：</label>\
                    <input type="number" name="check-score" class="form-control"\
                    style="width: 80px">\
                        </div>\
                        <button type="button" class="btn btn-primary" \
                        value="' + finishings[j].finishingId + '" onclick="homework_check(event)">确定</button>\
                        </form>\
                        </div>\
                        </h4>\
                        </div>\
                        <div id="collapse-' + panel_counter + j + '" class="panel-collapse collapse" role="tabpanel"\
                    aria-labelledby="heading-' + panel_counter + j + '">\
                        <div class="panel-body">' + answer + link + '</div>\
                    </div>\
                    </div>';
                            panel_group += panel;
                            //console.log(panel_group);
                            //console.log(panel);
                        }
                        panel_group += '</div>';
                        //console.log(panel_group);
                        homework_check_student.append(panel_group);
                        panel_counter++;
                    }
                });
            }
            $('.homework-check-list:first').css('display', 'block');
            $('.homework-check-list:first').find('button').eq(0).attr('disabled', true);
            $('.homework-check-list:last').find('button').eq(1).attr('disabled', true);
        }, 'json');
}

//作业批改
function homework_check(event) {
    var FinishiingId = $(event.target).val();
    var Score = $(event.target).parents('.check-score-form').find("[name='check-score']").val();
    $.post("http://123.206.80.54:7000/teach/mark", {
            loginToken: $.cookie('loginToken'),
            finishingId : FinishiingId,
            score : Score
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
        }, 'json');
}

//个人中心里发送短信
function pwd_change_validate() {
    var validate_button = $('#pwd-change-button');
    validate_button.attr('disabled', true);
    var time = 10;
    var clock = setInterval(function () {
        validate_button.text(time + "秒后可点击");
        time--;
        if (time < 0) {
            time = clearInterval(clock);
            validate_button.text("获取验证码");
            validate_button.attr('disabled', false);
        }
    }, 1000);
    var Mobile = $('#password-change-form').find("[name='mobile']").val();
    //console.log(Mobile);
    if (!Mobile) {
        console.log("test");
        var Username = $('#pwd-form').find("[name='username']").val();
        //console.log(Username);
        $.post("http://123.206.80.54:7000/user/validate", {
                username: Username
            },
            function (status, error, res) {
                $.cookie('mobileToken', res.responseJSON.res.mobileToken);
            }, 'json');
    } else {
        //console.log(Mobile,Username);
        $.post("http://123.206.80.54:7000/user/validate", {
                mobile: Mobile
            },
            function (status, error, res) {
                $.cookie('mobileToken', res.responseJSON.res.mobileToken);
            }, 'json');
    }
}

//个人中心里修改密码
function password_change() {
    var form = $('#password-change-form');
    var Password = form.find("[name='password']").val();
    var Password_repeat = form.find("[name='password-repeat']").val();
    var MobileToken = $.cookie('mobileToken');
    var Code = form.find("[name='code']").val();
    var Username = form.find("[name='username']").val();
    if(Password != Password_repeat){
        alert("两次密码输入不一致");
    }else{
        if (!Username) {
            var Mobile = form.find("[name='mobile']").val();
            $.post("http://123.206.80.54:7000/user/forget", {
                    mobile: Mobile,  //must be number
                    mobileToken: MobileToken, //填入短信验证时返回的结果
                    password: Password,
                    code: Code //填入手机收到的验证码
                },
                function (status, error, res) {
                    console.log("响应：" + res + "状态：" + status + "错误" + error);
                    location.reload();
                }, 'json');
        } else {
            $.post("http://123.206.80.54:7000/user/forget", {
                    username: Username, //不能为纯数字
                    mobileToken: MobileToken, //填入短信验证时返回的结果
                    password: Password,
                    code: Code //填入手机收到的验证码
                },
                function (status, error, res) {
                    console.log("响应：" + res + "状态：" + status + "错误" + error);
                    location.reload();
                }, 'json');
        }
        //console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
        //console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
        //+ typeof(Code) + ' ' + typeof(Mobile));
    }
}

//发帖
function article_post() {
    var form = $('#article-form');
    var ClassId = $('#course-nav').find('.active').find('a').attr('href').substring(1);
    var Title = form.find("[name='article-title']").val();
    var Content = form.find("[name='article-content']").val();
    var Top = false;
    var Enforce = false;
    if(form.find("[name='top']").is(':checked')){
        Top = true;
    }
    if(form.find("[name='enforce']").is(':checked')){
        Enforce = true;
    }
    //console.log("Enforce",Enforce);
    //console.log(Title,Content);
    $.post("http://123.206.80.54:7000/forum/post", {
            loginToken : $.cookie('loginToken'),
            classId : ClassId,
            top : Top, //置顶 学生设置此属性无效
            enforced : Enforce, //精品 学生设置此属性无效
            title : Title,
            content : Content
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
            location.reload();
        }, 'json');
}

//获取帖子列表
function article_list_get(event){
    var ClassId = $(event.target).attr('href').substring(1);
    var number = 1;
    $.post("http://123.206.80.54:7000/forum/list", {
            classId : ClassId,
            page : number
        },
        function (status, error, res) {
            var articles = res.responseJSON.res;
            var group = $('.article-list');
            var name;
            group.empty();
            for(var i = 0; i < articles.length; i++){
                $.ajax({
                    url : "http://123.206.80.54:7000/user/query",
                    async : false, // 注意此处需要同步
                    type : "POST",
                    dataType : "json",
                    data : {
                        loginToken: $.cookie('loginToken'),
                        userId : articles[i].userId
                    },
                    success : function(status, error, res) {
                        name = res.responseJSON.res.nickname;
                    }
                });
                var panel = '<div id="' + articles[i].id + '" class="panel panel-default">\
                    <div class="panel-heading" role="tab" id="heading-' + i + '">\
                    <h4 class="panel-title">\
                        <div class="row" style="margin: 0;text-align: center">\
                                <div class="col-xs-6">\
                    <a onclick="article_content_get(event)" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-' + i +  '" \
                    aria-expanded="true" aria-controls="collapse-' + i + '">' + articles[i].title +
                    '<span class="badge">' + articles[i].replyNum + '</span>' + '<small>' + name + ' ' +articles[i].updatedAt +
                    '</small>' + '</a>' +
                    '</div>\
                    <div class="col-xs-6">' +
                    '<small>回复：</small><input type="text" name="reply" style="width: 160px;">' +
                    '<div class="btn-group" role="group" aria-label="...">' +
                    '<button class="btn btn-danger btn-xs" onclick="delete_set(event)">删除</button>' +
                    '<button class="btn btn-success btn-xs" onclick="enforce_set(event)">加精</button>' +
                    '<button class="btn btn-info btn-xs" onclick="top_set(event)">置顶</button>' +
                    '<button class="btn btn-primary btn-xs" onclick="article_reply(event)">回复</button>' +
                    '</div>' +
                    '</div>\
            </div>\
    </h4>\
    </div>\
    <div id="collapse-' + i + '" class="panel-collapse collapse" role="tabpanel" \
                aria-labelledby="heading-' + i + '">\
                    <div class="panel-body">\
                    \
                    </div>\
                    <ul class="list-group">\
                    </ul>\
                </div>\
                </div>';
                group.append(panel);
            }
        }, 'json');
}

//获取帖子列表（分页）
function article_list_get_another(event){
    $('.pagination').find('li').removeClass('active');
    $(event.target).parent().addClass('active');
    var ClassId = $('#course-nav').find('.active').find('a').attr('href').substring(1);
    var Page = parseInt($(event.target).text());
    $.post("http://123.206.80.54:7000/forum/list", {
            classId : ClassId,
            page : Page
        },
        function (status, error, res) {
            var articles = res.responseJSON.res;
            var group = $('.article-list');
            var name;
            group.empty();
            for(var i = 0; i < articles.length; i++){
                $.ajax({
                    url : "http://123.206.80.54:7000/user/query",
                    async : false, // 注意此处需要同步
                    type : "POST",
                    dataType : "json",
                    data : {
                        loginToken: $.cookie('loginToken'),
                        userId : articles[i].userId
                    },
                    success : function(status, error, res) {
                        name = res.responseJSON.res.nickname;
                    }
                });
                var panel = '<div id="' + articles[i].id + '" class="panel panel-default">\
                    <div class="panel-heading" role="tab" id="heading-' + i + '">\
                    <h4 class="panel-title">\
                        <div class="row" style="margin: 0;text-align: center">\
                                <div class="col-xs-6">\
                    <a onclick="article_content_get(event)" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-' + i +  '" \
                    aria-expanded="true" aria-controls="collapse-' + i + '">' + articles[i].title +
                    '<span class="badge">' + articles[i].replyNum + '</span>' + '<small>' + name + ' ' +articles[i].updatedAt +
                    '</small>' + '</a>' +
                    '</div>\
                    <div class="col-xs-6">' +
                    '<small>回复：</small><input type="text" name="reply" style="width: 160px;">' +
                    '<div class="btn-group" role="group" aria-label="...">' +
                    '<button class="btn btn-danger btn-xs" onclick="delete_set(event)">删除</button>' +
                    '<button class="btn btn-success btn-xs" onclick="enforce_set(event)">加精</button>' +
                    '<button class="btn btn-info btn-xs" onclick="top_set(event)">置顶</button>' +
                    '<button class="btn btn-primary btn-xs" onclick="article_reply(event)">回复</button>' +
                    '</div>' +
                    '</div>\
            </div>\
    </h4>\
    </div>\
    <div id="collapse-' + i + '" class="panel-collapse collapse" role="tabpanel" \
                aria-labelledby="heading-' + i + '">\
                    <div class="panel-body">\
                    \
                    </div>\
                    <ul class="list-group">\
                    </ul>\
                </div>\
                </div>';
                group.append(panel);
            }
        }, 'json');
}


//回帖
function article_reply(event) {
    var ClassId = "5528a8ef-deda-41d6-a89e-6b36fcddcc1e";
    var Content = $(event.target).parent().prev().val();
    var TopicId = $(event.target).parents('.panel').attr('id');
    //console.log(ClassId,Content,TopicId);
    $.post("http://123.206.80.54:7000/forum/reply", {
            loginToken : $.cookie('loginToken'),
            classId : ClassId,
            topicId : TopicId,
            content : Content
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
        }, 'json');
}

//获取帖子内容和回复
function article_content_get(event) {
    var parent = $(event.target).parents('.panel');
    var TopicId = "http://123.206.80.54:7000/forum/" + parent.attr('id');
    //console.log(TopicId);
    var panel_body = parent.find('.panel-body');
    //onsole.log(panel_body);
    var ul = panel_body.next();
    ul.empty();
    var lis = '';
    $.get(TopicId,function(res,status){
        var article = res.res;
        //console.log(res.res.content);
        //console.log(res.responseJSON.res);
        panel_body.text(article.content);
        var replies = article.replies;
        var name;
        for(var i = 0; i < replies.length; i++){
            $.ajax({
                url : "http://123.206.80.54:7000/user/query",
                async : false, // 注意此处需要同步
                type : "POST",
                dataType : "json",
                data : {
                    loginToken: $.cookie('loginToken'),
                    userId : replies.userId
                },
                success : function(status, error, res) {
                    name = res.responseJSON.res.nickname;
                }
            });
            lis += '<li class="list-group-item">' + '<small>' + replies[i].createdAt + ' ' +name + ' </small>' + replies[i].content + '</li>';
        }
        ul.append(lis);
    });
}

//帖子置顶
function top_set(event) {
    var parent = $(event.target).parents('.panel');
    var TopicId = parent.attr('id');
    $.post("http://123.206.80.54:7000/forum/operate/top", {
            loginToken : $.cookie('loginToken'),
            topicId : TopicId
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
        }, 'json');
    location.reload();
}

//帖子加精
function enforce_set(event) {
    var parent = $(event.target).parents('.panel');
    var TopicId = parent.attr('id');
    //console.log(TopicId);
    $.post("http://123.206.80.54:7000/forum/operate/enforce", {
            loginToken : $.cookie('loginToken'),
            topicId : TopicId
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
        }, 'json');
    location.reload();
}

//帖子删除
function delete_set(event) {
    var parent = $(event.target).parents('.panel');
    var TopicId = parent.attr('id');
    $.post("http://123.206.80.54:7000/forum/operate/delete", {
            loginToken : $.cookie('loginToken'),
            topicId : TopicId
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
            location.reload();
        }, 'json');
}

function test_button1() {
    var Mobile = "18742011535";
    $.post("http://123.206.80.54:7000/user/validate", {
            mobile: Mobile
        },
        function (status, error, res) {
            //console.log("响应：" + res + "状态：" + status + "错误" + error);
            //console.log(res.responseText);
            //console.log(res.responseJSON.res);
            //console.log(res.responseJSON.res.mobileToken);
            $.cookie('mobileToken', res.responseJSON.res.mobileToken);
        }, 'json');
}

//测试用
function test_button2() {
    var FinishingId = "9e2090fc-0cd7-4b17-90f3-d28b98135faf";
//console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
//console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
//+ typeof(Code) + ' ' + typeof(Mobile));
    $.post("http://123.206.80.54:7000/answer/submit", {
            finishingId : FinishingId,
            content : "我已经背诵" //如果是自动批改的作业, 则遵循和/homework/create相同的规则.否则,可以是任意字符串
        },
        function (status, error, res) {
            console.log("响应：" + res + "状态：" + status + "错误" + error);
        }, 'json');
}

// function test_button2() {
//     var ClassId = "c478385d-9529-4b2b-81ae-af89fd6f5915";
// //console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
// //console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
// //+ typeof(Code) + ' ' + typeof(Mobile));
//     $.post("http://123.206.80.54:7000/homework/get", {
//             loginToken : $.cookie('loginToken'),
//             classId : ClassId
//         },
//         function (status, error, res) {
//             console.log("响应：" + res + "状态：" + status + "错误" + error);
//         }, 'json');
// }

// function test_button2() {
//     var Account = "18742011535";
//     var Password = "aspirin06";
// //console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
// //console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
// //+ typeof(Code) + ' ' + typeof(Mobile));
//     $.post("http://123.206.80.54:7000/user/login", {
//             account : Account,  //username or mobile number
//             password : Password,
//             remember : 7200  //(如果需要记住登录)登录记忆时长, 以秒(s)为单位
//         },
//         function (status, error, res) {
//             $.cookie('loginToken',res.responseJSON.res.loginToken);
//             console.log("响应：" + res + "状态：" + status + "错误" + error);
//         }, 'json');
// }

// function test_button2() {
//     var Type = 1;
//     var Username = "袁奇";
//     var Password = "aspirin06";
//     var MobileToken = $.cookie('mobileToken');
//     var Code = $('#test-code').val();
//     var Mobile = "18742011535";
// //console.log(Type + ' ' + Username + ' ' + Password + ' ' + MobileToken + ' ' + Code + ' ' + Mobile);
// //console.log( typeof(Type) + ' ' + typeof(Username) + ' ' + typeof(Password) + ' '+ typeof(MobileToken) + ' '
// //+ typeof(Code) + ' ' + typeof(Mobile));
//     $.post("http://123.206.80.54:7000/user/create", {
//             type: Type,  //0 = admin, 1 = student, 2 = teacher
//             username: Username, //不能为纯数字
//             password: Password,
//             mobile: Mobile,  //must be number
//             mobileToken: MobileToken, //填入短信验证时返回的结果
//             code: Code //填入手机收到的验证码
//         },
//         function (status, error, res) {
//             console.log("响应：" + res + "状态：" + status + "错误" + error);
//         }, 'json');
// }


